package com.Dao;

import com.bean.Remark;
import com.bean.Reply;
import com.tools.DButil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ReplyDao {
    //添加回复
    public void addReply(Reply reply)throws SQLException {
        String sql="insert into reply(author,pubtime,content,recontent,remarkId) value(?,?,?,?,?)";
        QueryRunner runner=new QueryRunner(DButil.getDataSource());
        runner.update(sql,reply.getAuthor(),reply.getPubtime(),reply.getContent(),reply.getReContent(),reply.getRemarkId());
    }

    //删除回复
    public void deleteReply(int id) throws SQLException {
        String sql="delete from reply where id=?";
        QueryRunner runner=new QueryRunner(DButil.getDataSource());
        runner.update(sql,id);
    }

    //显示所有回复
    public List<Reply> getAllReply(int remarkId) throws SQLException {
        String sql = "select * from reply where remarkId=? order by pubtime desc ";//根据时间降序，limit0，10——是指分页，10个数据一页
        QueryRunner runner = new QueryRunner(DButil.getDataSource());
        return runner.query(sql, new BeanListHandler<Reply>(Reply.class),remarkId);
    }

    //获取评论的发布时间
    public Date findPubTime(int id) throws SQLException {
        String sql="select pubtime from reply where id=?";
        QueryRunner runner=new QueryRunner(DButil.getDataSource());
        Date time= (Date) runner.query(sql,new ScalarHandler(),id);
        return time;

    }

    //查询单篇文章下的所有评论
    public  List<Reply> queryReply(int remarkId) throws SQLException {
        List list = new ArrayList();
        String sql = "select * from Reply where remarkId=? order by pubtime DESC";
        Reply reply = null;
        QueryRunner runner = new QueryRunner(DButil.getDataSource());
        List<Reply> rs = runner.query(sql, new BeanListHandler<Reply>(Reply.class),remarkId);
        if (rs != null) {
            for (int i = 0; i < rs.size(); i++) {
                reply = new Reply();
                reply.setId(rs.get(i).getId());
                reply.setRemarkId(rs.get(i).getRemarkId());
                reply.setAuthor(rs.get(i).getAuthor());
                reply.setContent(rs.get(i).getContent());
                reply.setReContent(rs.get(i).getReContent());
                reply.setPubtime(rs.get(i).getPubtime());

                list.add(reply);
            }
        }
        return list;
    }
    public int findAllCount(int articleId) throws SQLException {
        String sql="SELECT COUNT(*) FROM remark where articleid=? ";
        QueryRunner runner=new QueryRunner(DButil.getDataSource());
        Long count=(Long) runner.query(sql,new ScalarHandler(),articleId);
        return count.intValue();

    }
}
